import java.io.*;
import java.util.Scanner;

public class FinnalTest {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要搜索的文件的路径");
        String Path = sc.next();
        System.out.println("请输入你要查询的关键词");
        String searchWord = sc.next();

        File rootFile = new File(Path);
        if (!rootFile.isDirectory()) {
            System.out.println("输入的路径非法");
            return;
        }
        search(rootFile, searchWord);
    }
    
    private static void search(File rootFile,String searchWord) throws FileNotFoundException {
      File[] files = rootFile.listFiles();
      if(files == null) {
          System.out.println("该目录为空");
      }
      for (File f: files) {
          if(f.isFile()) {
              match(f,searchWord);
          }else if(f.isDirectory()){
              search(f,searchWord);
          }

      }

    }

    private static void match(File f, String searchWord) throws FileNotFoundException {
        try(Reader reader = new FileReader(f)) {
            StringBuilder stringBuilder = new StringBuilder();
            while(true) {
                Byte[] bytes = new Byte[1024];
                int c = reader.read();
                if(c == -1) {
                    break;
                }
                stringBuilder.append((char)c);
            }
            if(stringBuilder.indexOf(searchWord) > 0) {
                System.out.println("找到了匹配的结果：" + f.getAbsolutePath());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
